<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>沃商-聊天室</title>
    <link rel="stylesheet" href="/css/zui.min.css">
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/im.css">
    <link href="/css/jquery-sinaEmotion-2.1.0.min.css" rel="stylesheet">
    
    <script type="text/javascript" src="/js/swfobject.js"></script>
    <script type="text/javascript" src="/js/web_socket.js"></script>
    <script type="text/javascript" src="/js/jquery.min.js"></script>
    <script type="text/javascript" src="/js/zui.min.js"></script>

    <script type="text/javascript" src="/js/jquery-sinaEmotion-2.1.0.min.js"></script>
    <style>
        .sina-emotion{
            width:22px;
            height:22px;
        }
        *, *:before, *:after{
            box-sizing:border-box;
        }
        body, html{
            height:100%;
            overflow:hidden;
        }
        body, ul{
            margin:0;
            padding:0;
        }
        body{
            color:#4d4d4d;
            font:14px/1.4em 'Helvetica Neue', Helvetica, 'Microsoft Yahei', Arial, sans-serif;
            background:#f5f5f5 url('dist/images/bg.jpg') no-repeat center;
            background-size:cover;
            font-smoothing:antialiased;
        }
        ul{
            list-style:none;
        }
        #chat{
            margin:70px auto;
            width:880px;
            height:600px;
        }
        .m-title{
            padding:10px 15px;
            border-bottom:1px #E2E2E2 solid;
            background:#FBFBFB;
            position:relative;
        }
    </style>
    <script type="text/javascript">
    if (typeof console == "undefined") { this.console = {log: function (msg) { }};}
    // 如果浏览器不支持websocket，会使用这个flash自动模拟websocket协议，此过程对开发者透明
    WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
    // 开启flash的websocket debug
    WEB_SOCKET_DEBUG = true;
    var ws, name, client_list = {};
    var intervalId;

    // 连接服务器
    function connect() {
        ws = new WebSocket("ws://" + document.domain + ":7723");
        // 当socket连接打开时，输入用户名
        ws.onopen = onopen;
        // 当有消息时根据消息类型显示不同信息
        ws.onmessage = onmessage;
        ws.onclose = function () {
            console.log("连接关闭，定时重连");
            connect();
        };
        ws.onerror = function () {
            console.log("出现错误");
        };
    }

    function onopen() {
        if (!name) {
            show_prompt();
        }
        // 登录
        var login_data = '{"type":"login","client_name":"' + name.replace(/"/g, '\\"') + '","room_id":"<?php echo isset($_GET['room_id']) ? $_GET['room_id'] : 1?>"}';
        console.log("websocket握手成功，发送登录数据:" + login_data);
        ws.send(login_data);
    }

    function onmessage(e) {
        console.log(e.data);
        var data = JSON.parse(e.data);
        switch (data['type']) {
            // 服务端ping客户端
            case 'ping':
                ws.send('{"type":"pong"}');
                break;
                ;
            // 登录 更新用户列表
            case "login":
                console.info("用户登录");
                if (data['client_list']) {
                    client_list = data['client_list'];
                }
                else {
                    client_list[data['client_id']] = data['client_name'];
                }
                flush_client_list()
                console.info(client_list)
                console.log(data['client_name'] + "登录成功");
                new $.zui.Messager('提示消息：《' + data['client_name'] + '》登录', {
                    type: 'success' // 定义颜色主题
                }).show();
                break;
            case "say":
                console.info("用户发言");
                say(data['from_client_id'], data['from_client_name'], data['content'], data['time']);
                break;
            case "logout":
                console.info("用户退出");
                delete client_list[data['from_client_id']];
                flush_client_list();
                new $.zui.Messager('提示消息：《' + data['from_client_name'] + '》退出聊天室', {
                    type: 'danger' // 定义颜色主题
                }).show();
                break;
        }
    }

    // 刷新用户列表框
    function flush_client_list() {
        var i = 0;
        $("#user_list").empty();
        for (var p in client_list) {
            var user_html = " <li class=\"active\"><img class=\"avatar\" width=\"30\" height=\"30\"  src=\"dist/images/4.jpg\">\n" +
                "                    <p class=\"name\">" + client_list[p] + "</p>\n" +
                "                </li>"
            $("#user_list").append(user_html);
            i++;
        }
        $("#q-count").text(i)
    }

    // 输入姓名
    function show_prompt() {
        name = prompt('输入你的名字：', '');
        if (!name || name == 'null') {
            name = '游客';
        }
        $("#name").html(name);
    }

    document.onkeydown = function (event) {
        var e = event || window.event;
        var content = $("#content").val();
        if (e && e.keyCode == 13) { //回车键的键值为13
            if (content == '' || content == undefined){
                return false;
            }
            // 避免回车键换行
            e.preventDefault();
            $("#content").val("");
            var to_client_id = "all";
            var to_client_name = "测试";
            ws.send('{"type":"say","to_client_id":"' + to_client_id + '","to_client_name":"' + to_client_name + '","content":"' + content.replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '"}');
        }
    }

    // 发言
    function say(from_client_id, from_client_name, content, time) {
        //解析新浪微博图片
        content = content.replace(/(http|https):\/\/[\w]+.sinaimg.cn[\S]+(jpg|png|gif)/gi, function(img){
            return "<a target='_blank' href='"+img+"'>"+"<img src='"+img+"'>"+"</a>";}
        );

        //解析url
        content = content.replace(/(http|https):\/\/[\S]+/gi, function(url){
                if(url.indexOf(".sinaimg.cn/") < 0)
                    return "<a target='_blank' href='"+url+"'>"+url+"</a>";
                else
                    return url;
            }
        );
        
        //自己发言
        if (from_client_name == name) {
            var content_html = "<li>\n" +
                "                    <p class=\"time\"><span>" + time + "</span></p>\n" +
                "                    <div class=\"self\"><img class=\"avatar\" width=\"30\" height=\"30\" src=\"dist/images/1.jpg\">\n" +
                "                        <div class=\"text\"> " + content + "</div>\n" +
                "                    </div>\n" +
                "                </li>"
            $(".m-message").find("ul").append(content_html).parseEmotion();
            $(".m-message").scrollTop($(".m-message").find("ul").height());
        } else {
            var content_html = "<li>\n" +
                "                    <p class=\"time\"><span>" + time + "</span></p>\n" +
                "                    <div>\n" +
                "                        <img class=\"avatar\" width=\"30\" height=\"30\" src=\"dist/images/2.png\">\n" +
                "                        <span style=\"display:block;font-size:11px;color:#B2B4BB\">" + from_client_name + "</span>\n" +
                "                        <div class=\"text\" style=\"margin-top: 2px;\">" + content + "</div>\n" +
                "                    </div>\n" +
                "                </li>"
            $(".m-message").find("ul").append(content_html).parseEmotion();
            $(".m-message").scrollTop($(".m-message").find("ul").height());
            showMsgNotification("提醒", "您有一条新的消息", "http://im.woshangapp.com:55151/dist/images/1.jpg");
            $("title").html("您有一条新的消息")
            var title = $("title").html();
            var temptitle = title;
            var length = title.length;
            intervalId = setInterval(function () {
                temptitle = temptitle.concat(temptitle.charAt(0));
                length = temptitle.length;
                temptitle = temptitle.substring(1, length);
                $("title").html(temptitle);
            }, 1000);
        }
    }

    //当前窗口得到焦点
    window.onfocus = function () {
        //播放动画或视频
        clearInterval(intervalId)
        $("title").html("沃商-聊天室");
    };
    $(function () {
        select_client_id = 'all';
        $("#name").html(name);
        $("#m_list > ul > li").click(function () {
            $(this).addClass('active').siblings().removeClass('active');
            console.info($(this).attr("rootid"));
        });
        var isHiden = false;
        /*控制切换菜单*/
        $("#user_click").click(function () {
            if (isHiden) {
                $('#u-list').animate({right: '-=200px'});//菜单块向右移动
                $('#user_click').animate({right: '-=200px'});//菜单块向右移动
            } else {
                $('#u-list').animate({right: '+=200px'}); //菜单块向左移动
                $('#user_click').animate({right: '+=200px'}); //菜单块向左移动
            }
            isHiden = !isHiden;
        });
        
        $('.face').click(function(event){
            $(this).sinaEmotion($("#content"));
            event.stopPropagation();
        });

        

    });

    function showMsgNotification(title, msg, icon) {
        var options = {
            body: msg,
            icon: icon || "image_url"
        };
        var Notification = window.Notification || window.mozNotification || window.webkitNotification;
        if (Notification && Notification.permission === "granted") {
            var instance = new Notification(title, options);
            instance.onclick = function () {
                // Something to do
            };
            instance.onerror = function () {
                // Something to do
            };
            instance.onshow = function () {
                // Something to do
//                          setTimeout(instance.close, 3000);
                setTimeout(function () {
                    instance.close();
                }, 3000)
                console.log(instance.body)
            };
            instance.onclose = function () {
                // Something to do
            };
            console.log(instance)
        } else if (Notification && Notification.permission !== "denied") {
            Notification.requestPermission(function (status) {
                if (Notification.permission !== status) {
                    Notification.permission = status;
                }
                // If the user said okay
                if (status === "granted") {
                    var instance = new Notification(title, options);
                    instance.onclick = function () {
                        // Something to do
                    };
                    instance.onerror = function () {
                        // Something to do
                    };
                    instance.onshow = function () {
                        // Something to do
                        setTimeout(instance.close, 3000);
                    };
                    instance.onclose = function () {
                        // Something to do
                    };
                } else {
                    return false
                }
            });
        } else {
            return false;
        }
    }
    </script>
    <style type="text/css">#chat{overflow:hidden;border-radius:3px}
        #chat .main, #chat .sidebar{height:100%}
        #chat .sidebar{float:left;width:200px;color:#f4f4f4;background-color:#2e3238}
        #chat .main{position:relative;overflow:hidden;background-color:#eee}
        #chat .m-text{position:absolute;width:100%;bottom:0;left:0}
        #chat .m-message{height:calc(100% - 10pc)}</style>
    <style type="text/css">.m-card{padding:9pt;border-bottom:1px solid #24272c}
        .m-card footer{margin-top:10px}
        .m-card .avatar, .m-card .name{vertical-align:middle}
        .m-card .avatar{border-radius:2px}
        .m-card .name{display:inline-block;margin:0 0 0 15px;font-size:1pc}
        .m-card .search{padding:0 10px;width:100%;font-size:9pt;color:#fff;height:30px;line-height:30px;border:1px solid #3a3a3a;border-radius:4px;outline:0;background-color:#26292e}</style>
    <style type="text/css">
        .m-list li{padding:9pt 15px;border-bottom:1px solid #292c33;cursor:pointer;-webkit-transition:background-color .1s;transition:background-color .1s}
        .m-list li:hover{background-color:hsla(0, 0%, 100%, .03)}
        .m-list li.active{background-color:hsla(0, 0%, 100%, .1)}
        .m-list .avatar, .m-list .name{vertical-align:middle}
        .m-list .avatar{border-radius:2px}
        .m-list .name{display:inline-block;margin:0 0 0 15px}
        .u-list li{padding:5pt 15px;cursor:pointer;-webkit-transition:background-color .1s;transition:background-color .1s;font-size:13px;}
        .u-list li:hover{background-color:hsla(0, 0%, 100%, .03)}
        .u-list li.active{background-color:hsla(0, 0%, 100%, .1)}
        .u-list .avatar, .u-list .name{vertical-align:middle}
        .u-list .avatar{border-radius:2px}
        .u-list .name{display:inline-block;margin:0 0 0 5px}
    </style>
    <style type="text/css">.m-text{height:10pc;border-top:1px solid #ddd}
        .m-text textarea{padding:10px;height:100%;width:100%;border:none;outline:0;font-family:Micrsofot Yahei;resize:none}</style>
    <style type="text/css">.m-message{padding:10px 15px;overflow-y:scroll}
        .m-message li{margin-bottom:15px}
        .m-message .time{margin:7px 0;text-align:center}
        .m-message .time > span{display:inline-block;padding:0 18px;font-size:9pt;color:#fff;border-radius:2px;background-color:#dcdcdc}
        .m-message .avatar{float:left;margin:0 10px 0 0;border-radius:3px}
        .m-message .text{display:inline-block;position:relative;padding:3px 10px;max-width:calc(100% - 40px);min-height:30px;line-height:2.5;font-size:9pt;text-align:left;word-break:break-all;background-color:#fafafa;border-radius:4px}
        .m-message .text:before{content:" ";position:absolute;top:9px;right:100%;border:6px solid transparent;border-right-color:#fafafa}
        .m-message .self{text-align:right}
        .m-message .self .avatar{float:right;margin:0 0 0 10px}
        .m-message .self .text{background-color:#b2e281}
        .m-message .self .text:before{right:inherit;left:100%;border-right-color:transparent;border-left-color:#b2e281}</style>
</head>
<body onload="connect();">
<div id="chat" style="position:relative;">
    <!-- USER -->
    <div class="sidebar" id="u-list" style="float: right !important;background:#FBFBFB;border-left: 1px #E2E2E2 solid;color:black;position:absolute;right:-200px;z-index:99">
        <div style="border-bottom:1px #E2E2E2 solid;text-align:center;height:40px;line-height:40px;">
            <p class="name">群员</p>
        </div>
        <div class="u-list">
            <ul id="user_list" style="overflow: auto;height: 100%;">
                <li><img class="avatar" width="30" height="30" alt="webpack" src="dist/images/3.jpg">
                    <p class="name">webpack</p>
                </li>
            </ul>
        </div>
    </div>
    <!-- group -->
    <div class="sidebar">
        <div class="m-card">
            <header><img class="avatar" width="40" height="40" alt="Coffce" src="dist/images/1.jpg">
                <p class="name" id="name">Coffce</p>
            </header>
            <footer><input class="search" placeholder="search user..."></footer>
        </div><!--v-component-->
        <div class="m-list" id="m_list">
            <ul><!--v-for-start-->
                <li class="active" rootid="1">
                    <img class="avatar" width="30" height="30" alt="搬砖互喷群" src="dist/images/4.jpg">
                    <p class="name">搬砖互喷群</p>
                </li>
                <li rootid="2"><img class="avatar" width="30" height="30" alt="webpack" src="dist/images/3.jpg">
                    <p class="name">webpack</p>
                </li><!--v-for-end--></ul>
        </div><!--v-component--></div>
    <!-- Content -->
    <div class="main">
        <div class="m-title">
            <span>搬砖互喷群 (<i style="font-style:normal" id="q-count">0</i>)</span>
            <img id="user_click" src="dist/images/user.png" style="width:30px;position:absolute;right:10px;top:6px;"/>
        </div>
        <div class="m-message">
            <ul style="padding-bottom: 40px;"><!--v-for-start-->
                <li>
                    <p class="time"><span>15:59</span></p>
                    <div>
                        <img class="avatar" width="30" height="30" src="dist/images/2.png">
                        <span style="display:block;font-size:11px;color:#884898">脾气暴躁的临时工</span>
                        <div class="text" style="margin-top: 2px;">Hello，这是一个基于workerman构建的简单chat示例，请放心大胆的聊天不用怕。</div>
                    </div>
                </li>
                                              <!--v-for-end--></ul>
        </div><!--v-component-->
        <div class="m-text">
            <div style="background: #ffffff;" class="layui-unselect layim-chat-tool" data-json="%7B%22id%22%3A%227196F3C9D9EB933034029F592E41CB62%22%2C%22avatar%22%3A%22https%3A%2F%2Fthirdqq.qlogo.cn%2Fqqapp%2F101343857%2F7196F3C9D9EB933034029F592E41CB62%2F100%22%2C%22username%22%3A%22FG%22%2C%22sign%22%3A%22%22%2C%22status%22%3A%22online%22%2C%22name%22%3A%22FG%22%2C%22type%22%3A%22friend%22%7D">
                <span class="layui-icon layim-tool-face face" title="选择表情" layim-event="face"></span><span class="layui-icon layim-tool-image" title="上传图片" layim-event="image"><input type="file" name="file"></span><span class="layui-icon layim-tool-image" title="发送文件" layim-event="image" data-type="file"><input type="file" name="file"></span><span class="layui-icon layim-tool-video" title="视频" layim-event="extend" lay-filter="video"></span><span class="layui-icon layim-tool-voice" title="音频" layim-event="extend" lay-filter="voice"></span><span class="layim-tool-log" layim-event="chatLog"><i class="layui-icon"></i>聊天记录</span>
            </div>
            <textarea id="content" placeholder="按 Ctrl + Enter 发送"></textarea>
        </div><!--v-component-->
    </div>
</div>
</body>
</html>